﻿using MQTTnet.Protocol;
using MQTTnet.Server;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JESAI.MQTT.Server.Messages;

namespace JESAI.MQTT.Server
{
    public class MqttService
    {
        public static MqttServer _mqttServer { get; set; }

        public static void PublishData(string data)
        {
            var message = new MqttApplicationMessage
            {
                Topic = "topic_01",
                PayloadSegment = Encoding.Default.GetBytes(data),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                Retain = false  // 服务端是否保留消息。true为保留，如果有新的订阅者连接，就会立马收到该消息。
            };

            _mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(message) // 发送消息给有订阅 topic_01的客户端
            {
                SenderClientId = "SERVER"
            }).GetAwaiter().GetResult();
        }
        public static void PublishData(MqttByteArrayMessage mqttByteArrayMessage)
        {
            var message = new MqttApplicationMessage
            {
                Topic = mqttByteArrayMessage.Topic,
                PayloadSegment = mqttByteArrayMessage.Message,
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                Retain = false  // 服务端是否保留消息。true为保留，如果有新的订阅者连接，就会立马收到该消息。
            };

            _mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(message) // 发送消息给有订阅的客户端
            {
                SenderClientId = "SERVER"
            }).GetAwaiter().GetResult();
        }

        public static void PublishData(MqttStringMessage mqttStringMessage)
        {
            var applicationMessage = new MqttApplicationMessageBuilder()
                    .WithTopic(mqttStringMessage.Topic)
                    .WithPayload(mqttStringMessage.Message)
                    .Build();

            _mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(applicationMessage) // 发送消息给有订阅的客户端
            {
                SenderClientId = "SERVER"
            }).GetAwaiter().GetResult();
        }

        public static void PublishData(string Topic,string Message)
        {
            MqttStringMessage mqttStringMessage = new MqttStringMessage();
            mqttStringMessage.Message = Message;
            mqttStringMessage.Topic= Topic;

            PublishData(mqttStringMessage);
        }
    }
}
